package com.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bussiness.PoiInterface;
import com.bussiness.domain.Poi;
import com.bussiness.impl.PoiImpl;
import com.bussiness.domain.PoiTemplate.Type;

/**
 * Servlet implementation class CreateCustomPoi
 */
@WebServlet("/createpoitemp.html")
public class CreatePoiTemplate extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(CreatePoiTemplate.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CreatePoiTemplate() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = request
				.getRequestDispatcher("WEB-INF/pages/createpoitemp.jsp");
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Map<String, Type > poiMap = new HashMap<String, Type >();
		PoiInterface poi = new PoiImpl();
		String name = null;
		Type type = null;
		
		// Get attributtes, "name" : "Text, Banka"
		Map<String, String[]> map = request.getParameterMap();

		for (String key : map.keySet()) {
			String[] s = map.get(key);
			String value = s[0];
			
			try {
				type = Type.valueOf(s[1]);
			}catch(RuntimeException i){
				logger.info("Type not parrsed");
				continue;
			} 	
			
			if (value != null&& !value.trim().equals("")) {				
				if (type.equals(Type.Name)) {
					name = value;
				} else {
					poiMap.put(value, type);
				}	
			}
		}

		if (poiMap.size() > 0&& name != null) {
			logger.info("Create Poi template: " + name + "with values: " + poiMap);
			poi.createPoiTemplate(poiMap, name);
			//request.setAttribute("tempcreation", "");
		}else{
			logger.info("Poi template is not created ");
		}
		doGet(request, response);

	}

}
